import ibm_db
from django.contrib.auth.models import User

class DB2Backend(object):
    """
    Authenticate the user by connecting to the DB2 database that
    was specified when the authenticate function was called
    """

    supports_object_permissions = False
    supports_anonymous_user = False
    supports_inactive_user = False

    def authenticate(self, username=None, password=None, db=None, session=None):
        conn = ibm_db.connect(db, username, password)
        if conn:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username,password='xxxx')
                user.save()
            assert session is not None, "Can't store Db2 connection in session; session is missing"
            session['db2conn'] = conn
            session.set_expiry(300)
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


